﻿using System.Collections.Generic;
using System.Linq;
using ARMIR.util;
using LudeonTK;
using RimWorld;
using RimWorld.Planet;
using UnityEngine;
using Verse;
using Verse.AI.Group;
using Verse.Noise;
using static UnityEngine.GraphicsBuffer;


namespace ARMIR
{
    public class shieldTeamIncident : GameComponent {
        public shieldTeamIncident(Game game){ } //初始化组件什么的
        private bool isIncidentHappended; //是否已发生过袭击
        private Faction theFationIn; //迷迭香所在的阵营
        private bool beginExist; //当值为真时才开始检查阵营关系，通常而言，在游戏7日后开始检测
        private int relationChange; //关系变动值
        private int baseRelation; //基准关系值
        private int gapLog = 0;
        private bool incidentGoing; //袭击进行中，必须不断检查迷迭香状态以防止出现bug
        
        public override void StartedNewGame()
        {
            base.StartedNewGame();
            //初始化默认数据 
            isIncidentHappended = false;
            beginExist = false;
            setFactionForRosmontis();
            relationChange = 0;
            incidentGoing = false;
        }
        public override void ExposeData()
        {
            base.ExposeData();
            Scribe_Values.Look(ref isIncidentHappended, "是否已袭击过", false);
            Scribe_References.Look(ref theFationIn, "迷迭香所在阵营");
            Scribe_Values.Look(ref beginExist, "是否已播报过第一次加入", false);
            Scribe_Values.Look(ref relationChange, "关系差值", 0);
            Scribe_Values.Look(ref baseRelation, "基准关系值", 0);
            Scribe_Values.Look(ref incidentGoing, "袭击进行中", false);
        }
        public override void GameComponentTick()
        {
            base.GameComponentTick();
            gapLog++;
            if (gapLog > 1000) {
                //检查阵营状态并尝试赋值
                if (theFationIn == null) {
                    setFactionForRosmontis();
                }
                //检查关系,袭击尚未发生过则才检查
                if (!isIncidentHappended) {
                    factionRealtionDetect();
                }
                //ILog();
                gapLog = 0;
            }
            //袭击进行中使用的检查函数 
            if (isIncidentHappended) {
                checkRosmontis();
            }
        }
        /// <summary>
        /// 设置迷迭香所在的阵营
        /// </summary>
        private void setFactionForRosmontis() {
            List<Faction> factions = new List<Faction>();
            foreach (Faction faction in Find.FactionManager.AllFactions)
            {
                if (!faction.IsPlayer && !faction.defeated && faction.def != FactionDefOf.Insect
                    && faction.def != FactionDefOf.Ancients && faction.def != FactionDefOf.AncientsHostile
                    && faction.def != FactionDefOf.Mechanoid) { // 排除玩家阵营和已被击败的阵营
                    factions.Add(faction);
                }
            }
            if (ARMIR_ModSettings.randomFaction) {
                foreach (Faction faction in factions) {
                    //默认为友好外来者
                    if (faction.def == FactionDefOf.OutlanderCivil) { 
                        theFationIn = faction;
                        return;
                    }else if (faction.def == FactionDefOf.OutlanderRefugee
                        || faction.def == FactionDefOf.OutlanderRough
                        || faction.def == FactionDefOf.Empire) {
                        theFationIn = faction;
                        return;
                    }
                }
            }
            //在阵营中随机选择一个进行设置
            if (factions != null && factions.Count >= 1) {
                bool hasTheFaction = false;
                while (!hasTheFaction) { 
                    foreach (Faction faction in factions) {
                        float RandomChoose = UnityEngine.Random.value;
                        int relation = faction.RelationWith(Faction.OfPlayer).baseGoodwill;
                        if (RandomChoose < 0.5 && relation > -30) { 
                            theFationIn = faction;
                            //设置基准好感度
                            baseRelation = faction.RelationWith(Faction.OfPlayer,false).baseGoodwill;
                            hasTheFaction = true;
                            break;
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 检测玩家阵营与迷迭香所在阵营的关系
        /// </summary>
        private void factionRealtionDetect() {
            //在播报后才开始检查阵营关系
            if (beginExist) { 
                //获得当前的好感度
                FactionRelation realtionWithPlayerFaction = null;
                if (theFationIn != null) {
                    realtionWithPlayerFaction = theFationIn.RelationWith(Faction.OfPlayer, false);
                }
                int newRealtion = realtionWithPlayerFaction.baseGoodwill;
                //与基准好感度进行对比
                if (newRealtion - baseRelation < relationChange) {
                    relationChange = newRealtion - baseRelation;
                    //差值小于30后，第一次警告
                    if (relationChange <= -30 && relationChange > -60) {
                        //播报警告
                        ARMIR_language.isThatChinese(out bool yesItIs);
                        if (yesItIs) {
                            string title = theFationIn.Name + "的警告";
                            string body = "如果" + Faction.OfPlayer.Name + "再做出有损害于" + theFationIn.Name + "的可恶行径，他们将对你的殖民地做出恐怖的报复";
                            Find.LetterStack.ReceiveLetter(
                                title.Translate(), // 标题
                                body.Translate(), // 正文
                                LetterDefOf.NegativeEvent, // 信件定义
                                null, // 可选的点击目标
                                theFationIn // 可选的关联阵营（影响信件颜色等）
                            );
                        }else {
                            string title = "Warning from " + theFationIn.Name;
                            string body = "If you commit any actions that harm " + theFationIn + " again, you will be subjected by " + theFationIn + " terrifying retaliation against you.";
                            Find.LetterStack.ReceiveLetter(
                                title.Translate(), // 标题
                                body.Translate(), // 正文
                                LetterDefOf.NegativeEvent, // 信件定义
                                null, // 可选的点击目标
                                theFationIn // 可选的关联阵营（影响信件颜色等）
                            );
                        }
                        
                    }
                    //谈判破裂，准备攻坚
                    if (relationChange <= -60 && theFationIn.RelationKindWith(Faction.OfPlayer) == FactionRelationKind.Hostile) {
                        //执行袭击函数
                        doShieldTeamIncident(false,false);
                    }
                }else if (newRealtion - baseRelation > 30) {
                    //诺反而关系提升30，则重新设置基准好感度，以防止超低好感度无法生成袭击
                    baseRelation = newRealtion;
                }

            }else { //在游玩时间过一定天数后设定初始化开始检查关系
                //尝试播报
                if (GenDate.DaysPassed >= 7) { //游戏时间七天后尝试播报
                    beginExist = true;
                    ARMIR_language.isThatChinese(out bool yesItIs);
                    if (yesItIs) {
                        string title = theFationIn.Name + "得到了强大的力量";
                        string body = theFationIn.Name + "正在到处宣扬他们的强大，声称他们已经拥有了远超这片大地上其他存在的力量，并警告其他任何人不要再妄图有哪怕一点有害于" + theFationIn.Name + "的想法和行为，否则会招来灭顶之灾。\n\n也许最好不要主动招惹 " + theFationIn.Name + "，也许会有可怕的后果。" +
                            "\n\n(迷迭香现在加入了阵营 " + theFationIn + " ,诺今后与该阵营关系持续下降，可能会招致来自该阵营的特殊袭击)";
                        Find.LetterStack.ReceiveLetter(
                            title.Translate(), // 标题
                            body.Translate(), // 正文
                            LetterDefOf.NegativeEvent, // 信件定义
                            null, // 可选的点击目标
                            theFationIn // 可选的关联阵营（影响信件颜色等）
                        );
                    }else {
                        string title = theFationIn.Name + "now have a new strong power";
                        string body = theFationIn.Name + "They are boasting about their power everywhere, claiming they already possess strength far beyond any other beings on this land, and warning anyone else not to even attempt anything that might cause harm to " + theFationIn.Name +
                            "Otherwise, it will bring catastrophic consequences.\n\n" +
                            "\n\n(Now Rosmontis join the faction " + theFationIn + " ,If relations with this faction continue to decline, it will trigger special incident from this faction.)";
                        Find.LetterStack.ReceiveLetter(
                            title.Translate(), // 标题
                            body.Translate(), // 正文
                            LetterDefOf.NegativeEvent, // 信件定义
                            null, // 可选的点击目标
                            theFationIn // 可选的关联阵营（影响信件颜色等）
                        );
                    }
                    
                }
            }
        }
        private void doShieldTeamIncident(bool isShieldAttack,bool isAloneAttack) { 
            isIncidentHappended = true;
            
            //生成袭击
            Map map = Find.Maps[0];
            IntVec3 spawnCell;
            RCellFinder.TryFindRandomPawnEntryCell(out spawnCell, map, CellFinder.EdgeRoadChance_Hostile);
            float maxDistanceFromEdge = 50f;

            // 先尝试获取一个原版的地图边缘进入点
            IntVec3 mapCenter = map.Center;

            // 计算从边缘点到地图中心的方向向量（使用Vector3进行精确计算）
            Vector3 spawnVec = new Vector3(spawnCell.x, spawnCell.y, spawnCell.z);
            Vector3 centerVec = new Vector3(mapCenter.x, mapCenter.y, mapCenter.z);
            Vector3 directionToCenter = (centerVec - spawnVec).normalized; // 这里已经归一化

            // 尝试沿着向中心的方向移动一定距离，寻找一个合适的点
            int maxAttempts = 30;
            bool foundBetterCell = false;

            for (int i = 0; i < maxAttempts; i++)
            {
                // 计算移动距离（逐渐增加尝试距离）
                float progressRatio = (float)i / maxAttempts; // 0到1的进度
                int moveDistance = Mathf.Min((int)(Mathf.Min(map.Size.x, map.Size.z) * 0.1f * progressRatio),
                                            (int)maxDistanceFromEdge);

                // 确保最小移动距离
                moveDistance = Mathf.Max(moveDistance, 5);

                // 计算候选点（使用Vector3进行精确计算，然后取整到IntVec3）
                Vector3 candidateVec = spawnVec + directionToCenter * moveDistance;
                IntVec3 candidate = new IntVec3((int)candidateVec.x, (int)candidateVec.y, (int)candidateVec.z);

                // 确保新点在地图内且是有效的目的地
                if (candidate.InBounds(map))
                {
                    // 额外检查，确保从该点能到达殖民地
                    if (map.reachability.CanReachColony(candidate))
                    {
                        spawnCell = candidate;
                        foundBetterCell = true;
                        Log.Message($"找到更靠近中心的袭击点: {spawnCell} (距离中心: {spawnCell.DistanceTo(mapCenter)})");
                        break;
                    }
                }

                // 如果已经接近最大尝试次数，尝试一个更保守的距离
                if (i == maxAttempts - 1 && !foundBetterCell)
                {
                    // 最后尝试：只向中心移动一小段距离
                    int conservativeDistance = Mathf.Min(10, (int)maxDistanceFromEdge);
                    Vector3 conservativeCandidateVec = spawnVec + directionToCenter * conservativeDistance;
                    IntVec3 conservativeCandidate = new IntVec3((int)conservativeCandidateVec.x,
                                                               (int)conservativeCandidateVec.y,
                                                               (int)conservativeCandidateVec.z);

                    if (conservativeCandidate.InBounds(map) &&
                        
                        map.reachability.CanReachColony(conservativeCandidate))
                    {
                        spawnCell = conservativeCandidate;
                        foundBetterCell = true;
                        Log.Message($"使用保守的靠近中心点: {spawnCell}");
                    }
                }
            }

            if (!foundBetterCell)
            {
                Log.Message($"未找到更靠近中心的合适位置，使用原边缘点: {spawnCell}");
            }
            // 现在可以使用spawnCell作为袭击生成点

            //如果袭击发生在60天内则为小型袭击
            if (isShieldAttack) { 
                
            }else {
                // 设置延迟
                TickUtil DelayTick = Current.Game.GetComponent<TickUtil>();
                if (isAloneAttack) {
                    //执行空投袭击
                    doIncident();
                    //延迟后执行迷迭香空降
                    DelayTick.TickTimeManager(800, () => {
                        var BOSS_Alone = RosmontisGenerator.GenerateRosmontis(theFationIn, true);
                        var attacker = map.mapPawns.AllHumanlikeSpawned.Where(p => p.Faction == BOSS_Alone.Faction).ToList();
                        //优先寻找友军进行空降
                        if (attacker != null && attacker.Count > 0)
                        {
                            speDraw.DragLight(map, attacker[0].Position.ToVector3(), 30, 0.15f, 30, false, false, 120, 0.8f);
                            DelayTick.TickTimeManager(20, () => {
                                GenSpawn.Spawn(BOSS_Alone, attacker[0].Position, map);
                                var Rosmontis_Alone = map.mapPawns.AllPawnsSpawned.Where(p => p.health.hediffSet.HasHediff(DefDatabase<HediffDef>.GetNamed("ARMIR_OriginiumBrainStem"))).ToList();

                                foreach (SkillRecord skill in Rosmontis_Alone[0].skills.skills)
                                {
                                    if (skill.def == SkillDefOf.Melee)
                                    {
                                        skill.passion = Passion.Minor;
                                        skill.Level = 4;
                                    }
                                    if (skill.def == SkillDefOf.Shooting)
                                    {
                                        skill.passion = Passion.Major;
                                        skill.Level = 8;
                                    }
                                    if (skill.def == SkillDefOf.Intellectual)
                                    {
                                        skill.passion = Passion.Major;
                                        skill.Level = 4;
                                    }
                                }

                                Lord BOSSLord_Alone;
                                MakePawnSapper(Rosmontis_Alone[0], theFationIn, out BOSSLord_Alone);
                                //落地爆破特效
                                EffecterDef TMLand = DefDatabase<EffecterDef>.GetNamed("ARMIR_TMZeroTwo_EffecterA"); //技能特效
                                TMLand.Spawn(attacker[0].Position, map);
                                //爆破
                                List<Thing> ExplosiveIgnoredPawns = new List<Thing>();
                                ExplosiveIgnoredPawns.Add(Rosmontis_Alone[0]);
                                ExplosiveIgnoredPawns = map.mapPawns.AllPawnsSpawned.Where(p => p.Faction == Faction.OfPlayer && p.Position.DistanceTo(Rosmontis_Alone[0].Position) < 8).OfType<Thing>().ToList();
                                float randomDamageDef = UnityEngine.Random.value;
                                GenExplosion.DoExplosion(
                                    Rosmontis_Alone[0].Position,
                                    map,
                                    radius: 6,
                                    DamageDefOf.Crush,
                                    instigator: Rosmontis_Alone[0],
                                    damAmount: 24,
                                    armorPenetration: 0.4f,
                                    damageFalloff: false, //伤害随距离衰减开启
                                    screenShakeFactor: 1f, //屏幕震动强度(默认为1
                                    explosionSound: DefDatabase<SoundDef>.GetNamed("ARMIR_fakeEmpty"),
                                    ignoredThings: ExplosiveIgnoredPawns
                                );
                                annouROsmontis(Rosmontis_Alone[0]);
                            }, true);
                        }else {
                            GenSpawn.Spawn(BOSS_Alone, spawnCell, map);
                            var Rosmontis_Alone = map.mapPawns.AllPawnsSpawned.Where(p => p.health.hediffSet.HasHediff(DefDatabase<HediffDef>.GetNamed("ARMIR_OriginiumBrainStem"))).ToList();
                            Lord BOSSLord_Alone;
                            MakePawnSapper(Rosmontis_Alone[0], theFationIn, out BOSSLord_Alone);
                            annouROsmontis(Rosmontis_Alone[0]);
                        }
                    }, true);
                    return;
                }else {
                    if (GenDate.DaysPassed <= 60)
                    {
                        //执行空投袭击
                        doIncident();
                        //延迟后执行迷迭香空降
                        DelayTick.TickTimeManager(800, () => {
                            var BOSS_Alone = RosmontisGenerator.GenerateRosmontis(theFationIn, true);
                            var attacker = map.mapPawns.AllHumanlikeSpawned.Where(p => p.Faction == BOSS_Alone.Faction).ToList();
                            //优先寻找友军进行空降
                            if (attacker != null && attacker.Count > 0)
                            {
                                speDraw.DragLight(map, attacker[0].Position.ToVector3(), 30, 0.15f, 30, false, false, 120, 0.8f);
                                DelayTick.TickTimeManager(20, () => {
                                    GenSpawn.Spawn(BOSS_Alone, attacker[0].Position, map);
                                    var Rosmontis_Alone = map.mapPawns.AllPawnsSpawned.Where(p => p.health.hediffSet.HasHediff(DefDatabase<HediffDef>.GetNamed("ARMIR_OriginiumBrainStem"))).ToList();

                                    foreach (SkillRecord skill in Rosmontis_Alone[0].skills.skills)
                                    {
                                        if (skill.def == SkillDefOf.Melee)
                                        {
                                            skill.passion = Passion.Minor;
                                            skill.Level = 4;
                                        }
                                        if (skill.def == SkillDefOf.Shooting)
                                        {
                                            skill.passion = Passion.Major;
                                            skill.Level = 8;
                                        }
                                        if (skill.def == SkillDefOf.Intellectual)
                                        {
                                            skill.passion = Passion.Major;
                                            skill.Level = 4;
                                        }
                                    }

                                    Lord BOSSLord_Alone;
                                    MakePawnSapper(Rosmontis_Alone[0], theFationIn, out BOSSLord_Alone);
                                    //落地爆破特效
                                    EffecterDef TMLand = DefDatabase<EffecterDef>.GetNamed("ARMIR_TMZeroTwo_EffecterA"); //技能特效
                                    TMLand.Spawn(attacker[0].Position, map);
                                    //爆破
                                    List<Thing> ExplosiveIgnoredPawns = new List<Thing>();
                                    ExplosiveIgnoredPawns.Add(Rosmontis_Alone[0]);
                                    ExplosiveIgnoredPawns = map.mapPawns.AllPawnsSpawned.Where(p => p.Faction == Faction.OfPlayer && p.Position.DistanceTo(Rosmontis_Alone[0].Position) < 8).OfType<Thing>().ToList();
                                    float randomDamageDef = UnityEngine.Random.value;
                                    GenExplosion.DoExplosion(
                                        Rosmontis_Alone[0].Position,
                                        map,
                                        radius: 6,
                                        DamageDefOf.Crush,
                                        instigator: Rosmontis_Alone[0],
                                        damAmount: 24,
                                        armorPenetration: 0.4f,
                                        damageFalloff: false, //伤害随距离衰减开启
                                        screenShakeFactor: 1f, //屏幕震动强度(默认为1
                                        explosionSound: DefDatabase<SoundDef>.GetNamed("ARMIR_fakeEmpty"),
                                        ignoredThings: ExplosiveIgnoredPawns
                                    );
                                    annouROsmontis(Rosmontis_Alone[0]);
                                }, true);
                            }
                            else
                            {
                                GenSpawn.Spawn(BOSS_Alone, spawnCell, map);
                                var Rosmontis_Alone = map.mapPawns.AllPawnsSpawned.Where(p => p.health.hediffSet.HasHediff(DefDatabase<HediffDef>.GetNamed("ARMIR_OriginiumBrainStem"))).ToList();
                                Lord BOSSLord_Alone;
                                MakePawnSapper(Rosmontis_Alone[0], theFationIn, out BOSSLord_Alone);
                                annouROsmontis(Rosmontis_Alone[0]);
                            }
                        }, true);
                        return;
                    }
                }
            }
            
            //生成盾卫袭击
            doIncident();
            List<Pawn> RaidPawns = new List<Pawn>();
            for (int i = 0; i < 6; i++) {
                var shield = ShieldGenerator.GenerateShield(theFationIn);
                shield.health.RemoveAllHediffs();
                BodyPartRecord brainPart = shield.health.hediffSet.GetNotMissingParts().FirstOrDefault((BodyPartRecord x) => x.def == BodyPartDefOf.Head);
                if (brainPart != null)
                {
                    Hediff implant = HediffMaker.MakeHediff(DefDatabase<HediffDef>.GetNamed("ARMIR_marchInFormation"), shield, brainPart);
                    shield.health.AddHediff(implant);
                }
                RaidPawns.Add(shield);
            }
            if (RaidPawns.Count > 0) {
                foreach (Pawn a in RaidPawns) {
                    GenSpawn.Spawn(a, spawnCell, map);
                }
            }
            var BOSS = RosmontisGenerator.GenerateRosmontis(theFationIn,false);
            GenSpawn.Spawn(BOSS, spawnCell, map);
            var Rosmontis = map.mapPawns.AllPawnsSpawned.Where(p => p.health.hediffSet.HasHediff(DefDatabase<HediffDef>.GetNamed("ARMIR_OriginiumBrainStem"))).ToList();
            Lord BOSSLord;
            MakePawnSapper(Rosmontis[0], theFationIn, out BOSSLord);
            if (BOSSLord != null) { 
                var Shields = map.mapPawns.AllPawnsSpawned.Where(p => p.health.hediffSet.HasHediff(DefDatabase<HediffDef>.GetNamed("ARMIR_marchInFormation"))).ToList();
                if (Shields != null && Shields.Count > 0)
                {
                    foreach (var shield in Shields)
                    {
                        var lord = shield.GetLord();
                        if (lord != null)
                        {
                            lord.Notify_PawnLost(shield, PawnLostCondition.ForcedToJoinOtherLord); // 让Pawn脱离原有的Lord
                        }
                    }
                    LordJob_AssaultColony lordJob = new LordJob_AssaultColony(theFationIn, false, true, true, false, false);
                    LordMaker.MakeNewLord(theFationIn, lordJob, map, Shields);
                }
                //将盾卫设定为亲人,初始化迷迭香的笔记本
                ThingWithComps equippedWeapon = Rosmontis[0].equipment?.Primary;
                //确认武器是迷迭香的记事本
                if (equippedWeapon != null && equippedWeapon.def == DefDatabase<ThingDef>.GetNamed("ARMIR_Rosmontis_NoteBook"))
                {
                    //获取武器的动态数据组件
                    ThingComp_writeMemory weaponComp = equippedWeapon.GetComp<ThingComp_writeMemory>();
                    if (weaponComp != null)
                    {
                        if (Shields.Count > 0) {
                            foreach (Pawn a in Shields) {
                                weaponComp.FamilyNumbers.Add(a.ThingID);
                            }
                        }
                        weaponComp.recourdTimes = GenDate.DaysPassed - 7;
                        weaponComp.theFacton = theFationIn;
                    }
                }
            }
            //袭击播报
            ARMIR_language.isThatChinese(out bool yesItis);
            if (yesItis) {
                string title = "袭击：如你所愿";
                string body = "一支来自" + theFationIn.Name + "的装备精良的小队出现在了地图的边缘，他们的目的是摧毁你的殖民地，将你从这片大地上彻底抹除。";
                Find.LetterStack.ReceiveLetter(
                    title.Translate(), // 标题
                    body.Translate(), // 正文
                    LetterDefOf.ThreatBig, // 信件定义
                    Rosmontis[0], // 可选的点击目标
                    theFationIn // 可选的关联阵营（影响信件颜色等）
                );
            }else {
                string title = "Raid：AS YOUR WISH";
                string body = "A team from" + theFationIn.Name + "approach the rim of map,their purpose is to completely destroy your colony,Erase you from this land.";
                Find.LetterStack.ReceiveLetter(
                    title.Translate(), // 标题
                    body.Translate(), // 正文
                    LetterDefOf.ThreatBig, // 信件定义
                    Rosmontis[0], // 可选的点击目标
                    theFationIn // 可选的关联阵营（影响信件颜色等）
                );
            }
            
            incidentGoing = true;
        }
        private void doIncident() {
            // 1. 获取玩家地图
            Map map = Find.Maps[0];

            // 2. 设置袭击参数(袭击点数至少为1000)
            float points = StorytellerUtility.DefaultThreatPointsNow(map);
            if (points < 2000) {
                points = 2000;
            }
            IncidentParms parms = new IncidentParms
            {
                target = map,
                points = points,
                faction = theFationIn,
                raidStrategy = RaidStrategyDefOf.ImmediateAttack,
                raidArrivalMode = PawnsArrivalModeDefOf.CenterDrop
            };

            // 3. 生成并执行袭击
            IncidentDefOf.RaidEnemy.Worker.TryExecute(parms);
        }

        private void annouROsmontis(Pawn target) {
            //袭击播报
            ARMIR_language.isThatChinese(out bool yesItis);
            if (yesItis)
            {
                string title = "白色的菲林";
                string body = "一个看上去有些不同的敌人抵达了这里";
                Find.LetterStack.ReceiveLetter(
                    title.Translate(), // 标题
                    body.Translate(), // 正文
                    LetterDefOf.NegativeEvent, // 信件定义
                    target, // 可选的点击目标
                    theFationIn // 可选的关联阵营（影响信件颜色等）
                );
            }
            else
            {
                string title = "A White Enermy";
                string body = "An enemy that looks somewhat different has arrived here.";
                Find.LetterStack.ReceiveLetter(
                    title.Translate(), // 标题
                    body.Translate(), // 正文
                    LetterDefOf.NegativeEvent, // 信件定义
                    target, // 可选的点击目标
                    theFationIn // 可选的关联阵营（影响信件颜色等）
                );
            }
        }
        private void MakePawnSapper(Pawn pawn, Faction faction,out Lord lord)
        {
            // 1. 创建一个袭击殖民地的LordJob，并指定为工兵策略
            LordJob_AssaultColony lordJob = new LordJob_AssaultColony(faction, false, true, true, false, false);
            // 参数：派系, 可绑架, 可偷袭, 使用工兵行为, 无需迫击炮, 无需盾牌

            // 2. 创建一个新的Lord（集群AI），并指派给Pawn
            lord = pawn.GetLord();
            if (lord != null)
            {
                lord.Notify_PawnLost(pawn, PawnLostCondition.ForcedToJoinOtherLord); // 让Pawn脱离原有的Lord
            }
            LordMaker.MakeNewLord(faction, lordJob, pawn.Map, new List<Pawn> { pawn });
            // 现在这个Pawn就会遵循工兵的AI行为树了
        }

        private void checkRosmontis() {
            //获得到地图上的迷迭香
            Map map = Find.Maps[0];
            var Rosmontis = map.mapPawns.AllHumanlikeSpawned.Where(p => p.health.hediffSet.HasHediff(DefDatabase<HediffDef>.GetNamed("ARMIR_OriginiumBrainStem"))).ToList();
            //如果不存在迷迭香
            if (Rosmontis == null || Rosmontis.Count < 1)
            {
                //清理以免bug存在
                clearShieldJob();
                incidentGoing = false;
            }
            else {
                //或者迷迭香倒下了
                if (Rosmontis[0].Downed) {
                    clearShieldJob();
                    incidentGoing = false;
                }
            }
        }
        private void ILog() {
            if (theFationIn != null) {
                Log.Message("[DEBUG] 迷迭香当前所在阵营" + theFationIn.Name);
            }
            FactionRelation realtionWithPlayerFaction = null;
            if (theFationIn != null) {
                realtionWithPlayerFaction = theFationIn.RelationWith(Faction.OfPlayer, false);
                Log.Message("[DEBUG] 迷迭香当前所在阵营与玩家阵营的关系" + realtionWithPlayerFaction.baseGoodwill);
            }
            Log.Message("[DEBUG] 基准阵营关系" + baseRelation);
            Log.Message("[DEBUG] 差值阵营关系" + relationChange);
            Log.Message("[DEBUG] 是否已开始检查" + beginExist);
            Log.Message("[DEBUG] 经历天数" + GenDate.DaysPassed);
        }

        [DebugAction("Rosmontis In Rimworld", "Rosmontis Shield Team", actionType = DebugActionType.Action)]
        public static void SpawnRosmontisShieldTeam()
        {
            // 获取当前游戏的shieldTeamIncident实例
            shieldTeamIncident instance = Current.Game.GetComponent<shieldTeamIncident>();
            if (instance != null)
            {
                instance.doShieldTeamIncident(true,false);
            }
            else
            {
                Log.Error("shieldTeamIncident GameComponent not found!");
            }
        }

        [DebugAction("Rosmontis In Rimworld", "Rosmontis Incident Alone", actionType = DebugActionType.Action)]
        public static void SpawnRosmontisAttckAlone()
        {
            // 获取当前游戏的shieldTeamIncident实例
            shieldTeamIncident instance = Current.Game.GetComponent<shieldTeamIncident>();
            if (instance != null)
            {
                instance.doShieldTeamIncident(false,true);
            }
            else
            {
                Log.Error("shieldTeamIncident GameComponent not found!");
            }
        }

        [DebugAction("Rosmontis In Rimworld", "check Rosmontis Faction", actionType = DebugActionType.Action)]
        public static void RosmontisFaction()
        {
            // 获取当前游戏的shieldTeamIncident实例
            shieldTeamIncident instance = Current.Game.GetComponent<shieldTeamIncident>();
            if (instance != null)
            {
                Log.Message("[DEBUG] 迷迭香所在阵营是:" + instance.theFationIn);
                Log.Message("[DEBUG] 基准关系:" + instance.baseRelation);
                //获得当前的好感度
                FactionRelation realtionWithPlayerFaction = null;
                if (instance.theFationIn != null)
                {
                    realtionWithPlayerFaction = instance.theFationIn.RelationWith(Faction.OfPlayer, false);
                }
                int newRealtion = realtionWithPlayerFaction.baseGoodwill;
                //与基准好感度进行对比
                int relationChange = newRealtion - instance.baseRelation;
                Log.Message("[DEBUG] 基准关系与玩家派系关系差值(小于-60时发动袭击):" + relationChange);
                Log.Message("[DEBUG] 是否已发生过袭击(该袭击不会发生第二次)" + instance.isIncidentHappended);
                Log.Message(instance.beginExist);
                //神秘的英文 
                Log.Message("[DEBUG] The Faction Rosmontis in is" + instance.theFationIn);
                Log.Message("[DEBUG] The base relation with player" + instance.baseRelation);
                Log.Message("[DEBUG] if this number under -60,the incident will happen" + relationChange);
                Log.Message("[DEBUG] is the incident happend ?(this incident will not happen again)" + instance.isIncidentHappended);
            }
            else
            {
                Log.Error("呃呃，不知道出什么问题了,查不到迷迭香在哪个阵营捏");
            }
        }

        [DebugAction("Rosmontis In Rimworld", "clear shields Job", actionType = DebugActionType.Action)]
        public static void clearShieldJob()
        {
            //获取所有的盾卫
            Map map = Find.Maps[0];
            var shields = map.mapPawns.AllHumanlikeSpawned.Where(p => p.health.hediffSet.HasHediff(DefDatabase<HediffDef>.GetNamed("ARMIR_marchInFormation"))).ToList();
            shieldTeamIncident instance = Current.Game.GetComponent<shieldTeamIncident>();
            if (shields != null && shields.Count > 0) {
                foreach (var shield in shields) {
                    shield.jobs.StopAll();
                    shield.health.RemoveAllHediffs();
                    var lord = shield.GetLord();
                    if (lord != null)
                    {
                        lord.Notify_PawnLost(shield, PawnLostCondition.ForcedToJoinOtherLord); // 让Pawn脱离原有的Lord
                    }
                }
                if (instance != null)
                {
                    LordJob_AssaultColony lordJob = new LordJob_AssaultColony(instance.theFationIn, false, true, true, false, false);
                    LordMaker.MakeNewLord(instance.theFationIn, lordJob, shields[0].Map, shields);
                }
            }
        }

        [DebugAction("Rosmontis In Rimworld", "check Rosmontis Family", actionType = DebugActionType.Action)]
        public static void checkRosmontisFamily()
        {
            Map map = Find.CurrentMap;
            var Rosmontis = map.mapPawns.AllPawnsSpawned.Where(p => p.health.hediffSet.HasHediff(DefDatabase<HediffDef>.GetNamed("ARMIR_OriginiumBrainStem"))).ToList();
            if (Rosmontis[0] != null)
            {
                List<Pawn> pawns = map.mapPawns.AllHumanlikeSpawned;
                //记忆中的数据
                Hediff targetHediff = null;
                foreach (Hediff hediff in Rosmontis[0].health.hediffSet.hediffs)
                {
                    if (hediff.def.defName == "ARMIR_OriginiumBrainStem")
                    {
                        targetHediff = hediff;
                        break;
                    }
                }
                if (targetHediff != null)
                {
                    var pawnHediffComp = targetHediff.TryGetComp<HediffComp_familyRosmontis>();
                    Log.Message("[DEBUG] 迷迭香在阵营 " + Rosmontis[0].Faction + " 有记忆的生活天数是：" + pawnHediffComp.memoryRecordTimes);
                    Log.Message("[DEBUG] 迷迭香有记忆的家人数量是 " + pawnHediffComp.rememberFamily.Count + " 人");
                    Log.Message("[DEBUG] Rosmontis live in the faction " + Rosmontis[0].Faction + " for " + pawnHediffComp.memoryRecordTimes + " days");
                    Log.Message("[DEBUG] Rosmontis remember " + pawnHediffComp.rememberFamily.Count + " family");
                    List<string> ids = pawnHediffComp.rememberFamily;
                    //寻找地图上的家人
                    if (pawns != null)
                    {
                        foreach (Pawn pawn in pawns)
                        {
                            foreach (string id in ids)
                            {
                                if (pawn.ThingID == id)
                                {
                                    Log.Message("[DEBUG] Rosmontis's family:" + pawn.Name);
                                    break;
                                }
                            }
                        }
                    }
                }
                else {
                    Log.Message("[DEBUG] 呃呃，读不到迷迭香的记忆，不应该啊");
                }
                //记录中的数据
                ThingWithComps equippedWeapon = Rosmontis[0].equipment?.Primary;
                //确认武器是迷迭香的记事本
                bool hasNoteBook = false;
                if (equippedWeapon != null && equippedWeapon.def == DefDatabase<ThingDef>.GetNamed("ARMIR_Rosmontis_NoteBook"))
                {
                    //获取武器的动态数据组件
                    ThingComp_writeMemory weaponComp = equippedWeapon.GetComp<ThingComp_writeMemory>();
                    if (weaponComp != null)
                    {
                        hasNoteBook = true;
                        Log.Message("[DEBUG] 迷迭香的笔记本上记录了在阵营 " + weaponComp.theFacton + " 中生活了 " + weaponComp.recourdTimes + " 天");
                        Log.Message("[DEBUG] 迷迭香的笔记本中记录的家人数量是 " + weaponComp.FamilyNumbers.Count + " 人");
                        Log.Message("[DEBUG] Rosmontis's notebook record that she live in " + weaponComp.theFacton + " for " + weaponComp.recourdTimes + " days");
                        Log.Message("[DEBUG] Rosmontis's notebook record that she have " + weaponComp.FamilyNumbers.Count + " family");
                        List<string> ids = weaponComp.FamilyNumbers;
                        if (pawns != null)
                        {
                            foreach (Pawn pawn in pawns)
                            {
                                foreach (string id in ids)
                                {
                                    if (pawn.ThingID == id)
                                    {
                                        Log.Message("[DEBUG] Rosmontis's family on notebook:" + pawn.Name);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                if (hasNoteBook != true) {
                    Log.Message("[DEBUG] 迷迭香没装备笔记本，所以没有记录的记忆");
                }
            }
            else {
                Log.Message("[DEBUG] 未能找到目标以读取记忆,请在迷迭香在的地图上进行操作\n[DEBUG] no target founded to read memory, please try search on the map Rosmontis exist.");
            }
        }

        [DebugAction("Rosmontis In Rimworld", "Change Rosmontis Faction", actionType = DebugActionType.Action)]
        public static void ChangeRosmontisFaction()
        {
            // 获取当前游戏的shieldTeamIncident实例
            shieldTeamIncident instance = Current.Game.GetComponent<shieldTeamIncident>();
            if (instance != null)
            {
                if (instance.theFationIn != null) {
                    instance.setFactionForRosmontis();
                }
                Log.Message("[DEBUG] 重新修改迷迭香的派系为" + instance.theFationIn);
            }
            else
            {
                Log.Error("shieldTeamIncident GameComponent not found!");
            }
        }
    }
}